/**
 *FileName: GAGameStateHandler.js
 *Author: Abid Hussain
 *DateCreated: 
 */
exports.GAGameStateHandler = Core.Class.singleton({
	classname: 'GAGameStateHandler',
	initialize: function(){
		this._delegate = null;
		this._level = null;
		this._cExperience = null;
		this._sExperience = null;
		this._userkey = null;
		this._fileNames = null;
		this._gameDelegate = null;
		this._lastModifiedTime = 0;
		this._readCount = 0;
		this._fileCount = 0;
		this._udidStatePresent = true;
		this._userKeyStatePresent = true;
		this._serverLastModifiedTime = 0;
		this._storage = new Storage.KeyValue();
		this._dbPath = null;
		this._purchasedCoins = 0;
		this._purchasedBucks = 0;
		this._offerBucks = 0;
		this._offerCoins = 0;
		this._getConfigParams();
	},
	
	startGameState: function(delegate,gameDelegate){
		this._delegate = delegate;
		this._gameDelegate = gameDelegate;
		
		////zaki local 
		//this._getXPFromServer();
		this._isGameStateForCurrentUserPresent();

		//this.gameStateGetSuccess();
	},
	_getConfigParams: function(){
		this._fileNames = GAConfigurations.getDbFileNames();
		this._dbPath = GAConfigurations.getGameStateDBPath();
		this._userkey = GAConfigurations.getRecordID();
		this._saveXpKey = GAConfigurations.getGameCode()+GAConfigurations.getRecordID()+kGAGameState.kLastSavedXp;
	},
	
	_getXPFromServer: function(){
		var baseUrl = '';
		var responseObject = GAGameLoader.getResponseObject();
		if(responseObject != null){
			baseUrl = responseObject.getGameServer();	
		}
		baseUrl = baseUrl.replace('/gameState','/getGameStateInfo');
		var url = baseUrl+'?game='+GAConfigurations.getGameCode()+'&userkey='+this._userkey;
		var fetcher = new GAWebFetcher(this,30,0);
		fetcher.invokeGetRequest(url);
	},
	
	webFetchSuccess: function(webFetcher,response){
		try{
			var serverResponse = eval("("+ response +")");
			var status = serverResponse.status;
			if(status.code != 1){
				this._gameDelegate.readDataBase(this._dbPath,this.readDbSuccess.bind(this));
			}
			else{
				var data = serverResponse.data;
				this._sExperience = data.experience;
				var serverLMTime = data.gamestatelastupdatetime;
				serverLMTime  = this._dateFromUTC(serverLMTime, "-");
				this._serverLastModifiedTime = Date.parse(serverLMTime);
				this._saveExperience(this._sExperience);
				var path = this._dbPath+'/'+this._userkey;
				this._gameDelegate.readDataBase(path,this.readXpAndLevelSuccess.bind(this));
			}
		}
		catch(exception){
			this._delegate.gameStateFailure('>>Error while parsing GameStateInfo response = '+exception);
		}
		finally{
			if(webFetcher != null){
				webFetcher.destroy();
				webFetcher = null;
			}
		}
	},
	webFetchFailure: function(webFetcher,error){
		this._delegate.gameStateFailure('>>getGameStateInfo Failure = '+error);
		if(webFetcher != null){
			webFetcher.destroy();
			webFetcher = null;
		}
	},
	_saveExperience: function(value){
		this._storage.setItem(this._saveXpKey,value);
	},
	readDbSuccess: function(level,experience,offerCoins,offerBucks,purchasedCoins,purchasedBucks,fileNames){
		this._level = level;
		this._cExperience = experience;
		this._purchasedCoins = purchasedCoins;
		this._purchasedBucks = purchasedBucks;
		this._offerCoins = offerCoins;
		this._offerBucks = offerBucks;
		if(typeof(fileNames) != 'undefined' && fileNames != null){
			this._fileNames = this._fileNames.concat(fileNames);
			GAConfigurations.setDbFileNames(this._fileNames);
		}
		this._replaceGameState();
	},
	
	readXpAndLevelSuccess: function(level,experience,purchasedCoins,purchasedBucks,offerCoins,offerBucks,fileNames){
		this._level = level;
		this._cExperience = experience;
		if(typeof(fileNames) != 'undefined' && fileNames != null){
			this._fileNames = this._fileNames.concat(fileNames);
			GAConfigurations.setDbFileNames(this._fileNames);
		}
		this._isGameStateForCurrentUserPresent();
	},
	
	_replaceGameState: function (){
		var totalFiles = this._fileNames.length;
		for(var i=0; i< totalFiles; i++){
			var name = this._fileNames[i];
			Storage.FileSystem.readFile(this._dbPath+'/'+name+'.json',false,this._readFileCb.bind(this,name,totalFiles));
		}
	},
	_readFileCb: function(name,totalFiles,error, data){
		this._readCount ++;
		if(!error && this._udidStatePresent){
			Storage.FileSystem.writeFile(this._dbPath+'/'+this._userkey+'/'+name+'.json',data,this._writeFileCb.bind(this));	
		}
		else{
			this._udidStatePresent = false;
		}
		if(this._readCount == totalFiles){
			this._readCount = 0;
			if(this._udidStatePresent){
				//make call to read DB
				var currencyHandler = new GACurrencyUpdateHandler(this);
				currencyHandler.updateCurrency(this._purchasedCoins,this._purchasedBucks,this._offerCoins,this._offerBucks);
			}
			//if gameState against udid is not present
			else{
				// Fetch gameState for the current user
				GAGameStateGetHandler.restoreGameState(this);
			}
		}
	},
	_writeFileCb: function(error){
		if(error){
			this._delegate.gameStateFailure('>>Error while writing gameState = '+error);
		}
	},
	
	currencyUpdateSuccess: function(){
		GAGameStatePostHandler.postGameState(this,this._fileNames,this._level,this._cExperience);
	},
	currencyUpdateFailure: function(error){
		this._delegate.gameStateFailure('>>currencyUpdateFailure with error = '+error);
	},
	
	_isGameStateForCurrentUserPresent: function(){
		console.log("Zuluuu::: File Names "+this._fileNames);
		var totalFiles = this._fileNames.length;
		for(var i=0; i< totalFiles; i++){
			Storage.FileSystem.readFile(this._dbPath+'/'+this._userkey+'/'+this._fileNames[i]+'.json',this._readGameStateForUserCb.bind(this,totalFiles));
		}
	},
	_readGameStateForUserCb: function(totalFiles,error,data){
		this._fileCount ++;
		if(error){
			this._userKeyStatePresent = false;
		}
		if(this._fileCount == totalFiles){
			//game state exists
			if(this._userKeyStatePresent){
				//this._compareXPAndLMD();
				this._compareXP();
			}
			//game state does not exists
			else{
				// Fetch gameState for the current user
				GAGameStateGetHandler.restoreGameState(this);
				
				
				
				//GAGameStatePostHandler.postGameState(this,this._fileNames,this._level,this._cExperience);
			}
			this._fileCount = 0;
		}
	},

	_compareXP: function()
	{
		console.log("Zuluuu::: In Compare XP");
		var userXp = this._delegate._userXp;
		var serverXp = GAGameLoader.getResponseObject()._serverXp;
		
		console.log("Zuluuu::: UserXp "+userXp+"   Server XP "+serverXp);
		
		if(+userXp >= +serverXp)
		{
			// post maarni ha
			GAGameStatePostHandler.postGameState(this,this._fileNames,"0",userXp);
		}
		else
		{
			//restore maarna ha
			GAGameStateGetHandler.restoreGameState(this);
		}
	},
	
	_compareXPAndLMD: function(){
		//console.log('>>ClientXP = '+this._cExperience+' and ServerXP = '+this._sExperience);
		if(this._cExperience > this._sExperience){
			//postGameStatefor current user
			GAGameStatePostHandler.postGameState(this,this._fileNames,this._level,this._cExperience);
		}
		else if( this._cExperience < this._sExperience){
			//Fetch game state for current user
			GAGameStateGetHandler.restoreGameState(this);
		}
		else{
			this._getLMTimeOfClient();
		}
	},
	_getLMTimeOfClient: function(){
		this._storage.getItem(kGAGameState.kLastModifiedTime,this._getLMTimeCb.bind(this));
	},
	
	_getLMTimeCb: function(error,value,key){
		if(!error){
			this._lastModifiedTime = value;
		}
		//if(this._lastModifiedTime == this._serverLastModifiedTime){
        if(this._lastModifiedTime == -1 || this._lastModifiedTime == this._serverLastModifiedTime){ // Cheppi for first run
			//postGameStateFor current user
			GAGameStatePostHandler.postGameState(this,this._fileNames,"1","10");
		}
		else{
			//fetchGameStateforCurrentUser
			GAGameStateGetHandler.restoreGameState(this);
		}
	},
	
	_dateFromUTC: function( dateAsString, ymdDelimiter ){
		 var pattern = new RegExp( "(\\d{4})" + ymdDelimiter + "(\\d{2})" + ymdDelimiter + "(\\d{2}) (\\d{2}):(\\d{2}):(\\d{2})" );
		 var parts = dateAsString.match( pattern );
		 return new Date(Date.UTC(parseInt( parts[1] ), parseInt( parts[2], 10 ) - 1, parseInt( parts[3], 10 ), parseInt( parts[4], 10 ), parseInt( parts[5], 10 ), parseInt( parts[6], 10 ),0));
	},
	
	gameStateGetSuccess: function(){
		console.log('>>gameStateGetSuccess');
		this._delegate.gameStateSuccess();
	},
	gameStateGetFailure: function(error){
		this._delegate.gameStateFailure('>>gameStateGetFailure with error = '+error);
	},
	gameStatePostSuccess: function(){
		console.log('>>gameStatePostSuccess');
		/*var totalFiles = this._fileNames.length;
		for(var i=0; i< totalFiles; i++){
			Storage.FileSystem.deleteFile(this._dbPath+'/'+this._fileNames[i]+'.json');
		}*/
		this._delegate.gameStateSuccess();
	},
	gameStatePostFailure: function(error){	
		this._delegate.gameStateFailure('>>gameStatePostFailure with error = '+error);
	},
	destroy: function(){
		this._dbPath = null;
		this._fileNames = null;
		this._readCount = null;
		this._userkey = null;
		this._udidStatePresent = null;
		this._userKeyStatePresent = null;
		this._level = null;
		this._cExperience = null;
		this._sExperience = null;
		this._fileCount = null;
		this._lastModifiedTime = null;
		this._serverLastModifiedTime = null;
		this._storage = null;
		this._purchasedCoins = null;
		this._purchasedBucks = null;
		this._offerCoins = null;
		this._offerBucks = null;
		this._saveXpKey = null;
	}
});